package org.boulderfoodrescue.webapp.client.pickups.selectors;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.HasCloseHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.Widget;

public class CustomSelectorDialogView<T> extends Composite implements HasValue<T>, HasCloseHandlers<Boolean>{

	private static DonorSelectorDialogViewUiBinder uiBinder = GWT
			.create(DonorSelectorDialogViewUiBinder.class);

	@SuppressWarnings("rawtypes")
	interface DonorSelectorDialogViewUiBinder extends
			UiBinder<Widget, CustomSelectorDialogView> {
	}

	public CustomSelectorDialogView(SelectorInterface<T> selectorInterface) {
		initWidget(uiBinder.createAndBindUi(this));
		this.selectorInterface = selectorInterface;
		this.selectorInterface = selectorInterface;
		tableDiv.add(selectorInterface.getTable());
	}

	@UiField
	Button applyButton;
	@UiField
	Button cancelButton;
	@UiField
	FlowPanel tableDiv;
	
	private SelectorInterface<T> selectorInterface;

	@UiHandler("cancelButton")
	void onCancelButtonClick(ClickEvent e) {
		CloseEvent.fire(this, false);
	}
	
	@UiHandler("applyButton")
	void onApplyButtonClick(ClickEvent e) {
		CloseEvent.fire(this, true);
	}

	@Override
	public HandlerRegistration addValueChangeHandler(
			ValueChangeHandler<T> handler) {
		return addHandler(handler, ValueChangeEvent.getType());
	}

	@Override
	public T getValue() {
		return selectorInterface.getValue();
	}

	@Override
	public void setValue(T value) {
		selectorInterface.setValue(value);
		ValueChangeEvent.fire(this, value);
	}

	@Override
	public void setValue(T value, boolean fireEvents) {
		selectorInterface.setValue(value);
		if(fireEvents)
			ValueChangeEvent.fire(this, value);
	}

	@Override
	public HandlerRegistration addCloseHandler(CloseHandler<Boolean> handler) {
		return addHandler(handler, CloseEvent.getType());
	}

}
